package com.upf1sh.utils;

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.Encoder;
import ws.schild.jave.EncoderException;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.EncodingAttributes;
import ws.schild.jave.encode.VideoAttributes;
import ws.schild.jave.info.VideoInfo;
import ws.schild.jave.info.VideoSize;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class VideoCoderUtil {


    public static MultipartFile convertMultipartFileToMp4(MultipartFile multipartFile) throws IOException {

        if (!multipartFile.getOriginalFilename().endsWith("mp4")) {
            return multipartFile;
        }

        // 创建临时文件
        File tempInputFile = File.createTempFile("input", ".tmp");
        File tempOutputFile = File.createTempFile("output", ".mp4");

        try {
            // 将 MultipartFile 写入临时文件
            multipartFile.transferTo(tempInputFile);

            // 将临时文件转换为 MP4
            convertVideoToMp4(tempInputFile.getAbsoluteFile(), tempOutputFile.getAbsoluteFile());

            // 将转换后的文件读取为 MultipartFile
            FileInputStream inputStream = new FileInputStream(tempOutputFile);
            MultipartFile outputMultipartFile = new MockMultipartFile(
                    "output.mp4",
                    "output.mp4",
                    "video/mp4",
                    inputStream);

            return outputMultipartFile;
        } catch (EncoderException e) {
            throw new RuntimeException(e);
        } finally {
            // 删除临时文件
            tempInputFile.delete();
            tempOutputFile.delete();
        }
    }


    public static void convertVideoToMp4(File inputFile, File outputFile) throws EncoderException {
        // 创建编码器
        Encoder encoder = new Encoder();

        // 获取原视频信息
        MultimediaObject multimediaObject = new MultimediaObject(inputFile);
        VideoInfo videoInfo = multimediaObject.getInfo().getVideo();
        VideoSize size = videoInfo.getSize();
        int width = size.getWidth();
        int height = size.getHeight();
        int bitRate = videoInfo.getBitRate();
        float frameRate = videoInfo.getFrameRate();

        // 设置编码属性
        EncodingAttributes attributes = new EncodingAttributes();
        attributes.setOutputFormat("mp4");

        VideoAttributes video = new VideoAttributes();
        video.setCodec("libx264");
        video.setBitRate(bitRate);
        video.setFrameRate((int)frameRate);
        video.setSize(new VideoSize(width, height));

        attributes.setVideoAttributes(video);

        // 执行转换
        encoder.encode(multimediaObject, outputFile, attributes);
    }
}
